import * as actions from '../actions/index';
import dayjs from 'dayjs';

// 页面初始化数据
import intl from '../../../../../../../locale';

const initialState = {
  isLoading: false,
  curTab: window.location.hash ? window.location.hash.slice(1) : 'commits',
  mr_end_time: dayjs().format('YYYY-MM-DD'),
  mr_start_time: dayjs().subtract(7, 'day').format('YYYY-MM-DD'),
  commit_end_time: dayjs().format('YYYY-MM-DD'),
  commit_start_time: dayjs().subtract(7, 'day').format('YYYY-MM-DD'),
  commit_dimension: 'commit',
  commit_branch: intl.get({
    id: 'code-assets.projectInsight.reducers.All',
    defaultMessage: '全部',
  }),
  isLoadingCommit: true,
  total_commit: null,
  detail_commit: null,
  getTotalMrData: null,
  isLoadingTotalMr: true,
  total_mr: null,
  isLoadingDetailMr: true,
  detail_mr: [],
  isLoadingComment: true,
  comment_summary: null,
};

const defaultAction = {
  type: 'doNothing',
};

export default function index(state = initialState, action = defaultAction) {
  switch (action.type) {
    case actions.UPDATE_STATISTICS_DATA: {
      return { ...state, ...action.data };
    }
    case actions.DO_PERSONAL_CR_SORT: {
      const { key, order } = action.data;
      const newData = [...state.detail_mr];
      if (order === 'asc') {
        newData.sort((a, b) => {
          if (key === 'commitRate') {
            if (a.total_commits_count === 0) {
              return -1;
            }
            return (
              a.review_commits_count / a.total_commits_count -
              b.review_commits_count / b.total_commits_count
            );
          } else if (key === 'lineRate') {
            if (a.total_lines_count === 0) {
              return -1;
            }
            return (
              a.review_lines_count / a.total_lines_count -
              b.review_lines_count / b.total_lines_count
            );
          }
          return a[key] - b[key];
        });
      } else {
        newData.sort((a, b) => {
          if (key === 'commitRate') {
            if (b.total_commits_count === 0) {
              return -1;
            }
            return (
              b.review_commits_count / b.total_commits_count -
              a.review_commits_count / a.total_commits_count
            );
          } else if (key === 'lineRate') {
            if (b.total_lines_count === 0) {
              return -1;
            }
            return (
              b.review_lines_count / b.total_lines_count -
              a.review_lines_count / a.total_lines_count
            );
          }
          return b[key] - a[key];
        });
      }
      return { ...state, detail_mr: newData, isLoading: false };
    }
    default:
      return state;
  }
}
